package com.flyqiu.form.core.rule.valid;

import com.alibaba.fastjson2.JSONObject;
import com.flyqiu.form.api.rule.FlyQiuDataPropValidate;
import com.flyqiu.form.api.rule.FlyQiuFormDataRule;
import com.flyqiu.form.api.rule.FlyQiuValidateContext;
import com.flyqiu.form.api.tools.FlyQiuAvueColTools;
import com.flyqiu.form.common.enums.FlyQiuFormDataAction;
import com.flyqiu.form.common.exceptions.FormDataValidateException;
import com.flyqiu.form.model.entity.FlyQiuTableConfig;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

public class RequiredFlyQiuFormDataRule implements FlyQiuFormDataRule {
    /**
     * 数据项必填标识
     */
    public static final String KEY = "required";


    @Override
    public String getLabel() {
        return "必填";
    }

    @Override
    public String getValue() {
        return KEY;
    }


    @Override
    public FlyQiuDataPropValidate createDataValidate(JSONObject column, JSONObject rule) {
        if (!rule.containsKey("required")) {
            return null;
        }
        String message = rule.getString("message");
        if (StringUtils.isAllBlank(message)) {
            message = FlyQiuAvueColTools.getColumnLabel(column) + "不能为空！";
        }
        return new RequiredValidate(message);
    }


    public static class RequiredValidate implements FlyQiuDataPropValidate {
        private final String message;

        @Override
        public int getSort() {
            return Integer.MIN_VALUE;
        }

        public RequiredValidate(String message) {
            this.message = message;
        }


        @Override
        public void dataValidate(FlyQiuTableConfig config, JSONObject formData, Object data, FlyQiuFormDataAction action) {
            if (data == null) {
                throw new FormDataValidateException(message);
            }
            if (data instanceof Collection<?> && ((Collection<?>) data).isEmpty()) {
                throw new FormDataValidateException(message);
            }
        }

        @Override
        public void dataValidate(FlyQiuValidateContext context, Object valData, FlyQiuFormDataAction action) {
            if (valData == null) {
                throw new FormDataValidateException("在【" + context.getTableConfig().getFormName() + "】第" + (context.getRowIndex() + 1) + "行" + message);
            }
            if (valData instanceof Collection<?> && ((Collection<?>) valData).isEmpty()) {
                throw new FormDataValidateException("在【" + context.getTableConfig().getFormName() + "】第" + (context.getRowIndex() + 1) + "行" + message);
            }
        }
    }

}
